using Microsoft.Extensions.Logging;
using Microsoft.Win32;
using System;
using System.IO;
using System.Windows;

namespace DesktopHelper.Views
{
    public partial class SettingsWindow : Window
    {
        private readonly ILogger<SettingsWindow>? _logger;

        public SettingsWindow()
        {
            InitializeComponent();
            LoadSettings();
        }

        public SettingsWindow(ILogger<SettingsWindow> logger) : this()
        {
            _logger = logger;
        }

        private void LoadSettings()
        {
            try
            {
                // 加载当前设置
                // TODO: 从配置文件或注册表加载设置
                
                // 设置数据库路径
                var dbPath = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                    "DesktopHelper");
                DatabasePathTextBox.Text = dbPath;
                
                // 计算数据库大小
                CalculateDatabaseSize();
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "加载设置失败");
                MessageBox.Show($"加载设置失败：{ex.Message}", "错误", 
                               MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void CalculateDatabaseSize()
        {
            try
            {
                var dbPath = Path.Combine(DatabasePathTextBox.Text, "DesktopHelper.db");
                if (File.Exists(dbPath))
                {
                    var fileInfo = new FileInfo(dbPath);
                    var sizeInMB = fileInfo.Length / (1024.0 * 1024.0);
                    DatabaseSizeTextBlock.Text = $"{sizeInMB:F2} MB";
                }
                else
                {
                    DatabaseSizeTextBlock.Text = "未找到数据库文件";
                }
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "计算数据库大小失败");
                DatabaseSizeTextBlock.Text = "计算失败";
            }
        }

        private void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SaveSettings();
                MessageBox.Show("设置已保存", "成功", 
                               MessageBoxButton.OK, MessageBoxImage.Information);
                Close();
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "保存设置失败");
                MessageBox.Show($"保存设置失败：{ex.Message}", "错误", 
                               MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void SaveSettings()
        {
            // TODO: 保存设置到配置文件或注册表
            
            // 保存开机自启动设置
            if (AutoStartCheckBox.IsChecked == true)
            {
                SetAutoStart(true);
            }
            else
            {
                SetAutoStart(false);
            }
            
            _logger?.LogInformation("设置已保存");
        }

        private void SetAutoStart(bool enable)
        {
            try
            {
                var key = Registry.CurrentUser.OpenSubKey(
                    @"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                
                if (enable)
                {
                    var exePath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName;
                    if (!string.IsNullOrEmpty(exePath))
                    {
                        key?.SetValue("DesktopHelper", exePath);
                    }
                }
                else
                {
                    key?.DeleteValue("DesktopHelper", false);
                }
                
                key?.Close();
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "设置开机自启动失败");
                throw;
            }
        }

        private void OpenDatabaseFolderButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var path = DatabasePathTextBox.Text;
                if (Directory.Exists(path))
                {
                    System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                    {
                        FileName = path,
                        UseShellExecute = true,
                        Verb = "open"
                    });
                }
                else
                {
                    MessageBox.Show("文件夹不存在", "错误", 
                                   MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "打开数据库文件夹失败");
                MessageBox.Show($"打开文件夹失败：{ex.Message}", "错误", 
                               MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ClearOldDataButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var result = MessageBox.Show("确定要清理30天前的数据吗？此操作不可撤销。", 
                                            "确认清理", MessageBoxButton.YesNo, MessageBoxImage.Question);
                
                if (result == MessageBoxResult.Yes)
                {
                    // TODO: 实现清理30天前的数据
                    MessageBox.Show("数据清理完成", "成功", 
                                   MessageBoxButton.OK, MessageBoxImage.Information);
                    CalculateDatabaseSize();
                }
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "清理旧数据失败");
                MessageBox.Show($"清理失败：{ex.Message}", "错误", 
                               MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ClearAllDataButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var result = MessageBox.Show("确定要清空所有历史数据吗？此操作不可撤销。", 
                                            "确认清空", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                
                if (result == MessageBoxResult.Yes)
                {
                    // TODO: 实现清空所有数据
                    MessageBox.Show("所有数据已清空", "成功", 
                                   MessageBoxButton.OK, MessageBoxImage.Information);
                    CalculateDatabaseSize();
                }
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "清空所有数据失败");
                MessageBox.Show($"清空失败：{ex.Message}", "错误", 
                               MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void OptimizeDatabaseButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // TODO: 实现数据库优化（VACUUM）
                MessageBox.Show("数据库优化完成", "成功", 
                               MessageBoxButton.OK, MessageBoxImage.Information);
                CalculateDatabaseSize();
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "优化数据库失败");
                MessageBox.Show($"优化失败：{ex.Message}", "错误", 
                               MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ExportDataButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var dialog = new SaveFileDialog
                {
                    Filter = "JSON文件|*.json|所有文件|*.*",
                    DefaultExt = ".json",
                    FileName = $"DesktopHelper_Export_{DateTime.Now:yyyyMMdd}"
                };

                if (dialog.ShowDialog() == true)
                {
                    // TODO: 实现数据导出
                    MessageBox.Show("数据导出完成", "成功", 
                                   MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "导出数据失败");
                MessageBox.Show($"导出失败：{ex.Message}", "错误", 
                               MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ImportDataButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var dialog = new OpenFileDialog
                {
                    Filter = "JSON文件|*.json|所有文件|*.*",
                    DefaultExt = ".json"
                };

                if (dialog.ShowDialog() == true)
                {
                    var result = MessageBox.Show("导入数据将覆盖现有数据，确定要继续吗？", 
                                                "确认导入", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    
                    if (result == MessageBoxResult.Yes)
                    {
                        // TODO: 实现数据导入
                        MessageBox.Show("数据导入完成", "成功", 
                                       MessageBoxButton.OK, MessageBoxImage.Information);
                        CalculateDatabaseSize();
                    }
                }
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "导入数据失败");
                MessageBox.Show($"导入失败：{ex.Message}", "错误", 
                               MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}